<template>
  <div>
    <div>
      <el-form :inline="true" :model="trainingPlan" class="demo-form-inline">
        <el-form-item label="培训计划编号">
          <el-input v-model="trainingPlan.id" placeholder="请输入培训计划编号"></el-input>
        </el-form-item>
        <el-form-item label="培训计划名">
          <el-input v-model="trainingPlan.name" placeholder="请输入培训计划名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="show">查询</el-button>
          <el-button type="primary" @click="clear">清空</el-button>
        </el-form-item>

        <el-form-item style="float: left">
          <el-button type="primary" @click="add">新增</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="danger" @click="deleteByIds">批量删除选中</el-button>
        </el-form-item>

      </el-form>

      <div>
        <el-table
            max-height="400"
            highlight-current-row
            ref="multipleTable"
            tooltip-effect="dark"
            border
            @selection-change="handleSelectionChange"
            :data="tableData"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="name" label="培训计划名" header-align="center" align="center"></el-table-column>
          <el-table-column prop="type" label="培训类型" header-align="center" align="center"></el-table-column>
          <el-table-column prop="cycleId" label="培训周期" header-align="center" align="center">
            <template slot-scope="scope">
              {{ getTrainingCycle(scope.row.cycleId) }}天
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" header-align="center" align="center"></el-table-column>

          <el-table-column label="操作" width="400" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="updateInfo(scope.row.id)"
              >编辑
              </el-button>

              <el-button
                  size="mini"
                  type="danger"
                  plain
                  @click="deleteById(scope.row.id)"
              >删除
              </el-button>
              <el-button
                  v-show="scope.row.type==='有考试'"
                  size="mini"
                  type="primary"
                  plain
                  @click="addPaper(scope.row.id)"
              >配置试卷
              </el-button>
              <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="addDocumentVideo(scope.row.id)"
              >配置视频文档
              </el-button>

            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog title="信息" :visible.sync="dialogVisible" :before-close="close">
        <el-form :model="trainingPlan" size="mini">
          <el-form-item label="培训计划名" :label-width="formLabelWidth">
            <el-input v-model="trainingPlan.name" placeholder="请输入培训计划名" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="培训周期（单位:天）" :label-width="formLabelWidth">
            <el-select v-model="trainingPlan.cycleId" placeholder="请输入培训计划名" style="width:100%">
              <el-option
                  v-for="item in trainingCycleList"
                  :key="item.value"
                  :label="item.cycle"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="培训类型" :label-width="formLabelWidth">
            <el-select v-model="trainingPlan.type" placeholder="培训类型" style="width:100%">
              <el-option label="有考试" value="有考试"></el-option>
              <el-option label="无考试" value="无考试"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="培训开始日期" :label-width="formLabelWidth">
            <el-date-picker
                v-model="trainingPlan.beginTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-select v-model="trainingPlan.status" placeholder="培训类型" style="width:100%">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="已过期" value="已过期"></el-option>
            </el-select>
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false;clear()">取 消</el-button>
          <el-button type="primary" @click="addForm()">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="配置咨询列表" :visible.sync="configurePaperVisible" :before-close="closeConfigurePaper"
                 :fullscreen="true">
        <el-button style="float: left" type="primary" @click="addQuestionsToPaper" v-show="searchChoose ">批量添加
        </el-button>
        <el-button style="float: left" type="danger" @click="deleteQuestionsToPaper" v-show="!searchChoose ">批量删除
        </el-button>
        <el-switch
            v-model="searchChoose"
            active-text="试题库"
            inactive-text="试卷">
        </el-switch>
        <el-table
            max-height="400"
            highlight-current-row
            ref="testQuestionsTable"
            tooltip-effect="dark"
            border
            @selection-change="questionSelectionChange"
            :data="testQuestions"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="question" label="题目" header-align="center" align="center"></el-table-column>
          <el-table-column prop="type" label="类型" header-align="center" align="center"></el-table-column>
          <el-table-column prop="ans" label="答案" header-align="center" align="center"></el-table-column>
          <el-table-column prop="a" label="选项A" header-align="center" align="center"></el-table-column>
          <el-table-column prop="b" label="选项B" header-align="center" align="center"></el-table-column>
          <el-table-column prop="c" label="选项C" header-align="center" align="center"></el-table-column>
          <el-table-column prop="d" label="选项D" header-align="center" align="center"></el-table-column>
          <el-table-column label="操作" width="400" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="chooseQuestion(scope.row.id)"
                  v-show="searchChoose "
              >选择该题
              </el-button>
              <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="updateScoreShow(scope.row)"
                  v-show="!searchChoose "
              >配置分数
              </el-button>

              <el-button
                  size="mini"
                  type="danger"
                  plain
                  @click="unchooseQuestion(scope.row.id)"
                  v-show="!searchChoose "
              >删除该题
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>


      <el-dialog title="配置视频文档" :visible.sync="configureDocumentVideoVisible"
                 :before-close="closeConfigureDocumentVideo"
                 :fullscreen="true">
        <el-button style="float: left" type="primary" @click="addDocumentVideoToPaper" v-show="searchChoose ">批量添加
        </el-button>
        <el-button style="float: left" type="danger" @click="deleteDocumentVideoToPaper" v-show="!searchChoose ">批量删除
        </el-button>
        <el-switch
            v-model="searchChoose"
            active-text="视频文档库"
            inactive-text="视频文档">
        </el-switch>
        <el-table
            max-height="400"
            highlight-current-row
            ref="documentVideoTable"
            tooltip-effect="dark"
            border
            @selection-change="documentVideoChange"
            :data="documentVideos"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="name" label="文档视频类型名" header-align="center" align="center"></el-table-column>
          <el-table-column prop="type" label="文档视频类型名" header-align="center" align="center">
            <template slot-scope="scope">
              {{ getTypeName(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="400" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="chooseDocumentVideos(scope.row.id)"
                  v-show="searchChoose "
              >选择
              </el-button>

              <el-button
                  size="mini"
                  type="danger"
                  plain
                  @click="unchooseDocumentVideos(scope.row.id)"
                  v-show="!searchChoose "
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <el-dialog title="配置分数" :visible.sync="configureScoreVisible" :before-close="closeConfigureScore">
        <el-input type="number" placeholder="请输入分数" v-model="score"></el-input>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeConfigureScore">取 消</el-button>
          <el-button type="primary" @click="updateScores">确 定</el-button>
        </div>
      </el-dialog>


    </div>
    <br>
    <!--分页工具条-->
    <el-pagination
        style="position:absolute;bottom: 20px;margin-left: 40vh"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :background="background"
        :current-page="currentPage"
        :page-sizes="[5, 10]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
    </el-pagination>
  </div>


</template>
<script>


import {addTrainingPlan, changeTrainingPlan, deleteTrainingPlan, getAllTrainingPlan} from "@/api/trainingPlan";
import {getTrainingCycleList} from "@/api/trainingCycle";
import {chooseConsult, getConsultListForAgency, unchooseConsult} from "@/api/consult";
import {chooseQuestions, getScore, getTestQuestion, unchooseQuestions, updateScore} from "@/api/testPaper";
import {chooseDocumentVideo, getDocumentVideo, unchooseDocumentVideo} from "@/api/documentVideo";
import {getDocumentVideoTypeList} from "@/api/documentVideoType";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      trainingPlan: {},
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      trainingPlanList: [],
      formLabelWidth: "180px",
      trainingCycleList: [],//培训周期表
      //配置试卷
      configurePaperVisible: false,
      testPaper: {},
      trainingPlanId: '',
      searchChoose: true,
      questionSelection: [],
      testQuestions: [],
      //配置视频文档
      configureDocumentVideoVisible: false,
      documentVideos: [],
      documentVideoSelection: [],
      documentVideoTypeList: [],

      updateQuestion: {},//更新分数的题
      configureScoreVisible: false,
      score:'',
    }
  },
  watch: {
    searchChoose(newValue, oldValue) {
      this.getTestQuestions();
      this.getDocumentVideos();
    }
  },
  methods: {
    show() {
      getAllTrainingPlan(this.trainingPlan, this.currentPage, this.pageSize).then((res) => {
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          //console.log(this.tableData)
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show();
          }
        }
      }).catch((e) => {
      })
    },

    clear() {
      this.trainingPlan = {};
      this.show();
    },
    add() {
      this.trainingPlan = {};
      this.addOrUpdate = true;
      this.dialogVisible = true;
    },
    addForm() {
      if (this.addOrUpdate) {
        addTrainingPlan(this.trainingPlan).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        //更新
        changeTrainingPlan(this.trainingPlan).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.show()
          }
        }).catch(e => {
        });
      }

    },
    //获取视频文档类型
    getDocumentVideoTypeLists() {
      getDocumentVideoTypeList().then((res) => {
        if (res.data.code === 1) {
          this.documentVideoTypeList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    getTypeName(type) {
      const types = this.documentVideoTypeList.find(t => t.id === type);
      return types ? types.name : '未找到对应的类型';
    },
    //配置视频文档
    addDocumentVideo(id) {
      this.trainingPlanId = id;
      this.getDocumentVideos();
      this.configureDocumentVideoVisible = true;
    },
    closeConfigureDocumentVideo() {
      this.configureDocumentVideoVisible = false;
    },
    addDocumentVideoToPaper() {
      let selectedIds = [];
      //1. 创建id数组, 从 this.consultSelection 获取即可
      for (let i = 0; i < this.documentVideoSelection.length; i++) {
        selectedIds[i] = this.documentVideoSelection[i].id;
      }
      //console.log(selectedIds,this.trainingPlanId)
      chooseDocumentVideo(selectedIds, this.trainingPlanId).then((resp) => {
        if (resp.data.code === 1) {
          //配置成功
          this.$message.success("恭喜你，添加");
          this.getDocumentVideos();
        } else {
          this.$message.error(resp.data.msg);
        }
      }).catch(() => {
      });

    },
    deleteDocumentVideoToPaper() {
      // 弹出确认提示框
      this.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let selectedIds = [];
        //1. 创建id数组, 从 this.consultSelection 获取即可
        for (let i = 0; i < this.documentVideoSelection.length; i++) {
          selectedIds[i] = this.documentVideoSelection[i].id;
        }
        //console.log(selectedIds,this.trainingPlanId)
        unchooseDocumentVideo(selectedIds, this.trainingPlanId).then((resp) => {
          if (resp.data.code === 1) {
            //删除
            this.$message.success("恭喜你，删除成功");
            this.getDocumentVideos();
          } else {
            this.$message.error(resp.data.msg);
          }
        }).catch(() => {
        });

      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除");
      });
    },
    documentVideoChange(val) {
      this.documentVideoSelection = val;
    },
    getDocumentVideos() {
      getDocumentVideo(this.trainingPlanId, this.searchChoose).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          this.documentVideos = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    chooseDocumentVideos(id) {
      this.$refs.documentVideoTable.clearSelection();
      this.$refs.documentVideoTable.toggleRowSelection(this.documentVideos.filter(data => data.id === id)[0]);
      this.addDocumentVideoToPaper()
    },
    unchooseDocumentVideos(id) {
      this.$refs.documentVideoTable.clearSelection();
      this.$refs.documentVideoTable.toggleRowSelection(this.documentVideos.filter(data => data.id === id)[0]);
      this.deleteDocumentVideoToPaper();
    },


    //配置试卷
    addPaper(id) {
      this.trainingPlanId = id;
      this.getTestQuestions();
      this.configurePaperVisible = true;
    },
    closeConfigurePaper() {
      this.configurePaperVisible = false;
    },
    addConfigurePaper() {

    },
    addQuestionsToPaper() {
      let selectedIds = [];
      //1. 创建id数组, 从 this.consultSelection 获取即可
      for (let i = 0; i < this.questionSelection.length; i++) {
        selectedIds[i] = this.questionSelection[i].id;
      }
      //console.log(selectedIds,this.trainingPlanId)
      chooseQuestions(selectedIds, this.trainingPlanId).then((resp) => {
        if (resp.data.code === 1) {
          //配置成功
          this.$message.success("恭喜你，添加");
          this.getTestQuestions();
        } else {
          this.$message.error(resp.data.msg);
        }
      }).catch(() => {
      });

    },
    deleteQuestionsToPaper() {
      // 弹出确认提示框
      this.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let selectedIds = [];
        //1. 创建id数组, 从 this.consultSelection 获取即可
        for (let i = 0; i < this.questionSelection.length; i++) {
          selectedIds[i] = this.questionSelection[i].id;
        }
        //console.log(selectedIds,this.trainingPlanId)
        unchooseQuestions(selectedIds, this.trainingPlanId).then((resp) => {
          if (resp.data.code === 1) {
            //删除
            this.$message.success("恭喜你，删除成功");
            this.getTestQuestions();
          } else {
            this.$message.error(resp.data.msg);
          }
        }).catch(() => {
        });

      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除");
      });
    },
    questionSelectionChange(val) {
      this.questionSelection = val;
    },
    getTestQuestions() {
      getTestQuestion(this.trainingPlanId, this.searchChoose).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          this.testQuestions = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    chooseQuestion(id) {
      this.$refs.testQuestionsTable.clearSelection();
      this.$refs.testQuestionsTable.toggleRowSelection(this.testQuestions.filter(data => data.id === id)[0]);
      this.addQuestionsToPaper()
    },
    unchooseQuestion(id) {
      this.$refs.testQuestionsTable.clearSelection();
      this.$refs.testQuestionsTable.toggleRowSelection(this.testQuestions.filter(data => data.id === id)[0]);
      this.deleteQuestionsToPaper();
    },


    //配置分数
    updateScoreShow(question) {
      console.log(question);
      this.updateQuestion = question;
      getScore(this.trainingPlanId,question.id).then((res) => {
          if(res.data.code===1){
            this.score=res.data.data;
            this.configureScoreVisible = true;
          }
      }).catch((e) => {})
    },
    closeConfigureScore() {
      this.configureScoreVisible = false;
    },
    updateScores() {
      updateScore(this.trainingPlanId,this.updateQuestion.id,this.score).then((res) => {
        if (res.data.code === 1) {
          this.$message.success("更新成功")
          this.configureScoreVisible = false;
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch((e) => {
      })
    },

    close() {
      this.dialogVisible = false;
      this.trainingPlan = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.trainingPlan = this.tableData.filter(data => data.id == id)[0];
      this.dialogVisible = true;
    },
    deleteById(id) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(this.tableData.filter(data => data.id === id)[0]);
      this.deleteByIds()
    },
    deleteByIds() {
      // 弹出确认提示框
      this.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //用户点击确认按钮
        //1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id;
        }
        //console.log(this.selectedIds);
        deleteTrainingPlan(this.selectedIds).then((resp) => {
          if (resp.data.code == "1") {
            //删除成功
            this.$message.success("恭喜你，删除成功");
            this.clear();
          } else {
            this.$message.error(resp.data.msg);
          }
        }).catch(() => {
        });

      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除");
      });

    },

    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },

    //获取培训周期列表
    getTrainingCycleLists() {
      getTrainingCycleList().then((res) => {
        if (res.data.code === 1) {
          this.trainingCycleList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    getTrainingCycle(id) {
      let trainingCycle = this.trainingCycleList.find(data => data.id === id);
      return trainingCycle ? trainingCycle.cycle : "";
    }


  },
  mounted() {
    this.show();
    this.getTrainingCycleLists();
    this.getDocumentVideoTypeLists();
  },
};
</script>


<style>
* {
  margin: 0;
  padding: 0;
}

.el-header {
  background-color: rgb(238, 241, 246);
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: white;
}

</style>
<script setup>
import testQuestion from "@/views/TestQuestion.vue";
import {addDocumentVideoType} from "@/api/documentVideoType";
import {updateScore} from "@/api/testPaper";
</script>
